package model

import (
	"log"
	"time"

	"gitee.com/nanakura/imgui-restclient/db"
	sq "github.com/Masterminds/squirrel"
)

type History struct {
	Id          int32
	Method      string
	Url         string
	Headers     string
	Params      string
	Body        string
	Response    string
	ContentType int32 `db:"content_type"`
	Date        time.Time
	Time        int32
}

func InsertHistory(history History) error {
	sb := sq.StatementBuilder
	sql, args, _ := sb.Insert("history").
		Columns("method", "url", "headers", "params", "body", "content_type", "response", "date", "time").
		Values(history.Method, history.Url, history.Headers, history.Params, history.Body, history.ContentType, history.Response, history.Date, history.Time).
		ToSql()
	_, err := db.Db.MustExec(sql, args...).RowsAffected()
	if err != nil {
		log.Println(err)
		return err
	}
	return nil
}

func GetHistory() ([]History, error) {
	res := make([]History, 0)
	sb := sq.StatementBuilder
	sql, args, _ := sb.Select("*").From("history").ToSql()

	err := db.Db.Select(&res, sql, args...)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	return res, nil
}

func ClearHistory() error {
	_, err := db.Db.MustExec("DELETE FROM history;").RowsAffected()
	if err != nil {
		log.Println(err)
	}
	return err
}

func RemoveHistoryById(id int32) error {
	sb := sq.StatementBuilder
	sql, args, _ := sb.Delete("history").
		Where(sq.Eq{"id": id}).
		ToSql()
	_, err := db.Db.MustExec(sql, args...).RowsAffected()
	if err != nil {
		log.Println(err)
	}
	return err
}
